package com.hr.mes.controller;

import com.hr.mes.dto.Page;
import com.hr.mes.dto.Result;
import com.hr.mes.entity.Role;
import com.hr.mes.enums.MyExceptionEnum;
import com.hr.mes.exception.MyException;
import com.hr.mes.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequiresRoles("admin")
@Api(tags = "角色管理")
@CrossOrigin
@RequestMapping("/api/role")
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ApiOperation("新增角色")
    @PostMapping("addRole")
    public Result addRole(@RequestBody Role role){
        try{
            roleService.addRole(role);
            return Result.ok();
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.ROLE_ADD_ERROR, e);
        }
    }

    @ApiOperation("删除角色")
    @GetMapping("deleteRole")
    public Result deleteRole(@RequestParam Integer roleId){
        try{
            roleService.deleteRole(roleId);
            return Result.ok();
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.ROLE_DELETE_ERROR, e);
        }
    }

    @ApiOperation("更新角色")
    @PostMapping("updateRole")
    public Result updateRole(@RequestBody Role role){
        try{
            roleService.updateRole(role);
            return Result.ok();
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.ROLE_UPDATE_ERROR, e);
        }
    }

    @ApiOperation("查询角色")
    @GetMapping("getRole")
    public Result getRole(@RequestParam Integer roleId){
        try{
            Role role = roleService.getRole(roleId);
            return Result.ok(role);
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.ROLE_VIEW_ERROR, e);
        }
    }

    @ApiOperation("查询所有角色")
    @GetMapping("getRoleList")
    public Result getRoleList(@RequestParam Integer pageNo, @RequestParam Integer pageSize){
        try{
            Page<Role> roleList = roleService.getRoleList(pageNo, pageSize);
            return Result.ok(roleList);
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.ROLE_VIEW_ERROR, e);
        }
    }

    @ApiOperation("查询所有可用的角色")
    @GetMapping("getAvailableRoleList")
    public Result getAvailableRoleList(){
        try{
            List<Role> roleList = roleService.getAvailableRoleList();
            return Result.ok(roleList);
        }catch (Exception e){
            throw new MyException(MyExceptionEnum.ROLE_VIEW_ERROR, e);
        }
    }

}
